/*
 * Copyright (c) 2019.  drakelee.base All rights reserved.
 */

package com.base.components.common.util;

import net.ipip.ipdb.IPFormatException;
import net.ipip.ipdb.Reader;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.io.InputStream;

/**
 * IpLocationUtil
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version 1.0.0, 2018-05-10 13:42
 */
public class IpLocationUtil {
  /** 自定义新的数据库文件，优先加载 */
  public static final String CUSTOM_DB_FILE = "custom-ip-db.ipdb";
  /** 默认数据库文件 */
  public static final String DEFAULT_DB_FILE = "default-ip-db.ipdb";

  private static Reader READER;

  /**
   * 查询IP位置
   * @param ipv4 - ipv4
   * @return [国家, 省, 市, 区县（一般空字符串）]
   */
  public static String[] find(String ipv4){
    if("localhost".equalsIgnoreCase(ipv4)){
      ipv4 = "127.0.0.1";
    }
    try {
      String[] array = getReader().find(ipv4, "CN");
      if(array != null){
        int valCount = 0;
        for (int i = 0; i < array.length; i++) {
          if (StringUtils.isBlank(array[i])) {
            array[i] = null;
          }else{
            valCount++;
          }
        }
        if(valCount == array.length){
          return array;
        }
        else{
          String[] re = new String[valCount];
          for (int i = 0; i < array.length; i++) {
            if(array[i] != null){
              re[i] = array[i];
            }
          }
          return re;
        }
      }
    } catch (IPFormatException e) {
      throw new IllegalArgumentException(ipv4 + " 不是IPV4", e);
    } catch (Exception e) {
      throw new IllegalArgumentException(ipv4 + " 解析出错", e);
    }
    return new String[0];
  }

  public static String findToString(String ipv4){
    return StringUtils.join(find(ipv4), "-");
  }

  public static String findToString(String ipv4, String split){
    return StringUtils.join(find(ipv4), split);
  }

  private static Reader getReader() {
    if(READER == null){
      READER = newReader(CUSTOM_DB_FILE);
    }
    if(READER == null){
      READER = newReader(DEFAULT_DB_FILE);
    }
    Assert.notNull(READER, "未找到IP数据库文件，" + CUSTOM_DB_FILE + " 或 " + DEFAULT_DB_FILE);
    return READER;
  }

  private static Reader newReader(String file){
    try(InputStream inputStream = IpLocationUtil.class.getClassLoader().getResourceAsStream(file)){
      if(inputStream != null){
        return new Reader(inputStream);
      }
    }catch (Exception ignore){
    }
    return  null;
  }
}